package com.qf3.utils;

import com.qf3.advices.ServiceAdvice;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Properties;

public class BeanFactory {

    //将通知对象创建
    private static ServiceAdvice serviceAdvice = new ServiceAdvice();

    public static Object getBean(String beanId)  {

        try {
            Properties properties = new Properties();
            properties.load(BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"));

            String className = properties.getProperty(beanId);

            Object obj = Class.forName(className).newInstance();

            //返回代理对象
            return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                    //只需要对find相关的方法做增强
                    String methodName = method.getName();
                    if (methodName.startsWith("find")) {

                        serviceAdvice.around_my(obj,method,args);

//                        try {
//                            serviceAdvice.before(); //前置增强
//                            //执行目标对象方法
//                            Object invoke = method.invoke(obj, args);
//
//                            serviceAdvice.afterReturning(); //返回后增强
//                            return invoke;
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                            serviceAdvice.afterThrowing(); //异常增强
//                        } finally {
//                            serviceAdvice.after(); //最终增强
//                        }

                        return null;
                    }else{
                        //执行原本的目标方法
                        return method.invoke(obj, args);
                    }
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }
}
